"use strict";

import Vue from 'vue';
import qs from "qs";
import axios from "axios";

const baseHost = 'http://front.cd2c19dacf66e4107927b899d29ced135.cn-beijing.alicontainer.com';
// const baseHost = 'http://47.95.191.104:9090';
// 测试APP
// let appid = "wxef27587ef160c7cf";
let appid = "wx69b369d98aed296e";
// 测试用户
let openid = "ohWbQ541fPKTYGT5VqAuhv0z9dE8";

// 获得 query 参数
let getParameterByName = function (name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[[\]]/g, '\\$&');
    var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, ' '));
};

let version = "v101";

let setCookie = (name,value,days) => {
    name = version + name;
    let expires = "";
    if (days) {
        let date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "")  + expires + "; path=/";
};
let getCookie = (name) => {
    name = version + name;
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) === ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
    }
   return null;
};
let eraseCookie = (name) => {
    name = version + name;
    document.cookie = name+'=; Max-Age=-99999999;';
};

{
    // let debug = location.hostname.indexOf(":") > 0;
    let debug = location.hostname === 'localhost';
    if (!debug) {
        // 从域名前缀中获得 appid
        let host = window.location.hostname.replace(/^(www\.)/,""); // 去除 www. 前缀，某些浏览器或爬虫会自动加上 www. 前缀
        appid = host.substr(0, host.indexOf("."));
        // 登陆成功之后跳回当前页面，并会在 query 参数中带上 openid
        openid = getParameterByName("customer_openid");
        if(openid) {
            // 设置到本地 cookie 中
            setCookie("openid", openid, 30);
            // history.replaceState(null, '', )
        } else {
            openid = "";
            // 从 cookie 中获得 openid
            let localOpenid = getCookie("openid");
            if(localOpenid){
                openid = localOpenid;
            }
        }
    }
}
// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

let config = {
    baseURL: baseHost,
    appid: appid,
    openid: openid,
    // 退出登陆
    logout(){
        eraseCookie("openid")
    },
    // 跨域时不能带上 cookie, 因此需要将所有跨域链接加上用户信息
    linkUrl(url) {
        url = this.baseURL + url;
        let sep = "?";
        if(url.indexOf("?")>0) {
            sep = "&"
        }
        url = url + sep + "customer_appid=" + appid;
        if (openid) {
            url +=  "&customer_openid=" + openid
        }
        return url
    },
    timeout: 15 * 1000,
    withCredentials: false, // Check cross-site Access-Control
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
    }
};
let responseFilter = (response)=> {
    let data = response.data;
    if (data) {
        // 授权跳转
        if (data.redirect) {
            location.href = data.redirect
        }
        return response
    }
};
// 请求预处理
let requestParser = (config) => {
    let method = config.method.toUpperCase();
    if (method === "POST" || method==="PUT") {
        config.data = qs.stringify(config.data,{arrayFormat: 'brackets'});
    }
    if(config.params && config.params.unset) {
        config.params = null;
    } else {
        config.params = {
            customer_appid: appid,
            customer_openid: openid,
            ...config.params // 保留原来的参数
        };
    }
    return config;
};
const _axios = axios.create(config);
_axios.interceptors.request.use(requestParser,  (error) => {
    return Promise.reject(error);
});

// Add a response interceptor
_axios.interceptors.response.use(responseFilter,
    function(error) {
        return Promise.reject(error);
    }
);

Plugin.install = function(Vue, options) {
  Vue.axios = _axios;
  window.axios = _axios;
  Object.defineProperties(Vue.prototype, {
    axios: {
      get() {
        return _axios;
      }
    },
    $axios: {
      get() {
        return _axios;
      }
    },
  });
};
Vue.use(Plugin)

export default Plugin;
